from django.core.paginator import Paginator, EmptyPage
from django.views import View
from django.http import JsonResponse
from .models import SKU, GoodsCategory
from .utils import get_breadcrumb


class ListView(View):
    def get(self, request, category_id):

        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        # 上面时获取参数，下面是获取数据库的数据，根据catrgory_id
        skus = SKU.objects.filter(
            category_id=category_id,
            is_launched=True  # 这个时判断商品是否下架
        ).order_by(ordering)
        # 调用类函数获取查询集
        paginator = Paginator(skus, page_size)
        print('总数量', paginator.count)
        print('总页数', paginator.num_pages)
        # 分页操作实现
        try:
            cur_page = paginator.page(page)
        except EmptyPage as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '空页'})
        ret_list = []
        for sku in cur_page:
            ret_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image_url.url,
                'name': sku.name,
                'price': sku.price
            })
        breadcrumb = get_breadcrumb(category_id)
        return JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'breadcrumb': breadcrumb,
            'list': ret_list,
            'count': paginator.num_pages
        })


class HotGoodsView(View):
    def get(self, request, category_id):
        skus = SKU.objects.filter(
            category_id=category_id,
            is_launched=True
        ).order_by('-sales')[0:2]
        ret_list = []
        for sku in skus:
            ret_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image_url.url,
                'name': sku.name,
                'price': sku.price
            })
        return JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'hot_skus': ret_list
        })


from haystack.views import SearchView


class MySearchView(SearchView):
    def create_response(self):
        context = self.get_context()

        sku_list = []
        for search_result in context['page'].object_list:
            sku = search_result.object
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image_url.url,
                'searchkey': context['query'],
                'page_size': context['paginator'].per_page,
                'count': context['paginator'].count
            })

        return JsonResponse(sku_list, safe=False)
